﻿using System;
using Microsoft.Xna.Framework;

namespace ThreeDWorld
{
    public class Animation
    {
        private Sequence _Seq;
        private int _I;
        private float _Amount;

        public Animation()
        {
            _Seq = new Sequence(0, 0, 0, false);

            Reset();
        }

        public bool Done
        {
            get;
            private set;
        }

        public BoundingBox Bounds
        {
            get;
            private set;
        }

        public Sequence Sequence
        {
            get { return _Seq; }

            set
            {
                if (!_Seq.Equals(value))
                {
                    _Seq = value;

                    Reset();
                }
            }
        }

        public void Reset()
        {
            _I = _Seq.StartFrame;
            _Amount = 0;

            Done = _Seq.StartFrame == _Seq.EndFrame;
        }

        public void Update(KeyFrameMesh mesh, float elapsedTime)
        {
            int i = _I;
            int j = _I + 1;

            if (i == _Seq.EndFrame)
            {
                j = _Seq.StartFrame;
            }
            Bounds = mesh.KeyFrames[i].LerpBounds(mesh.KeyFrames[j], _Amount);

            if (Done)
            {
                return;
            }

            _Amount += _Seq.Speed * elapsedTime;

            if (_Amount >= 1)
            {
                if (_Seq.Looping)
                {
                    if (_I == _Seq.EndFrame)
                    {
                        _I = _Seq.StartFrame;
                    }
                    else
                    {
                        _I++;
                    }
                    _Amount = 0;
                }
                else
                {
                    if (_I == _Seq.EndFrame - 1)
                    {
                        _Amount = 1;

                        Done = true;
                    }
                    else
                    {
                        _I++;
                        _Amount = 0;
                    }
                }
            }

            i = _I;
            j = _I + 1;

            if (i == _Seq.EndFrame)
            {
                j = _Seq.StartFrame;
            }
            Bounds = mesh.KeyFrames[i].LerpBounds(mesh.KeyFrames[j], _Amount);
        }

        public void Draw(KeyFrameMesh mesh)
        {
            int i = _I;
            int j = _I + 1;

            if (i == _Seq.EndFrame)
            {
                j = _Seq.StartFrame;
            }
            mesh.Draw(i, j, _Amount);
        }
    }
}
